package com.cy.milktea.service.impl;

import com.cy.milktea.common.annotation.SetUserAndTime;
import com.cy.milktea.mapper.MenuMapper;
import com.cy.milktea.mapper.RoleMenuMapper;
import com.cy.milktea.pojo.Menu;
import com.cy.milktea.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @SetUserAndTime
    @Override
    public int add(Menu menu) {
        return menuMapper.insert(menu);
    }

    @Transactional
    @Override
    public int delete(Integer id) {
        //删除前先判断是否还有role中含有该menu
        int count = roleMenuMapper.selectCountMenuId(id);
        if (count == 0) {
            //查询其含有的子菜单并删除
            List<Integer> ids = menuMapper.selectChildren(id);
            ids.add(id);
            return menuMapper.delete(ids.toArray(new Integer[ids.size()]));
        }
        return -1;
    }

    @SetUserAndTime(value = "modify")
    @Override
    public int update(Menu menu) {
        return menuMapper.update(menu);
    }

    @Override
    public Map<String, Object> queryAll() {
        List<Menu> menus = menuMapper.selectAll();
        Map<String, Object> map = new HashMap<>(2);
        //获取菜单列表
        List<Integer> list = new ArrayList<>(menus.size());
        for (Menu menu : menus) {
            list.add(menu.getId());
        }
        map.put("menuIds", list);
        //菜单树化
        map.put("menus", Menu.toTreeLastNoChildren(menus));
        return map;
    }

    @Override
    public List<Menu> queryByRoleId(Integer roleId) {
        return menuMapper.selectByRoleId(roleId);
    }
}















